package demo4;

import demo3.Person;
import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * @description:运行时类的方法结构
 * @author:Mr.Cat
 * @create:2021-11-23 14:27
 **/
public class MethodTest {
    @Test
    public void test1() {
        Class clazz = Person.class;
        //获取方法
        //getMethods():获取当前运行时类及其父类中声明为public的方法
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }
        System.out.println();

        //getDeclaredMethods():获取运行时类当中声明的所有方法（不包含父类中声明的方法）
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method method : declaredMethods
        ) {
            System.out.println(method);
        }
    }

    //权限修饰符  返回值类型 方法名（参数类型1 形参名1、参数类型2 形参名2……）throws xxxException{}
    @Test
    public void test2() {

        Class clazz = Person.class;
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method method:declaredMethods) {
            //获取方法声明的注解
            Annotation[] annotations = method.getAnnotations();
            for (Annotation a:annotations) {
                System.out.print(a);
            }
            //权限修饰符
            System.out.print(Modifier.toString(method.getModifiers()) + "\t");

            //返回值类型
            System.out.print(method.getReturnType()+"\t");

            //方法名
            System.out.print(method.getName());
            System.out.print("(");

            //形参列表
            Class[] parameterTypes = method.getParameterTypes();
            if(!(parameterTypes==null&&parameterTypes.length==0)){
                for (int i=0;i<parameterTypes.length;i++) {
                    if(i==parameterTypes.length-1){
                        System.out.print(parameterTypes[i].getName()+"\targs_"+i);
                        break;
                    }
                    System.out.print(parameterTypes[i].getName()+"\targs_"+i+",");
                }

            }
            System.out.print(")");
            //抛出的异常
            Class[] exceptionTypes = method.getExceptionTypes();
            if(exceptionTypes.length>0){
                System.out.print("throws");
                for (int i=0;i<exceptionTypes.length;i++){
                    if(i==exceptionTypes.length-1){
                        System.out.print(exceptionTypes[i].getName());

                    }
                    System.out.print(exceptionTypes[i].getName()+",");

                }
            }

            System.out.println();
        }
    }
}

